package com.ficus.road.maintain.file;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ReflectUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author xiawen yang
 * @date 2022/6/20 下午8:57
 */
@Slf4j
public class FileClientFactoryImpl implements FileClientFactory {

    /**
     * 文件客户端 Map
     * key：配置编号
     */
    private final ConcurrentMap<String, AbstractFileClient<?>> clients = new ConcurrentHashMap<>();

    @Override
    public FileClient getFileClient(String clientName) {
        AbstractFileClient<?> client = clients.get(clientName);
        if (client == null) {
            log.error("[getFileClient][配置名称({}) 找不到客户端]", clientName);
        }
        return client;
    }

    @Override
    public <Config extends FileClientConfig> void createFileClient(String clientName, Config config) {
        AbstractFileClient<Config> client = (AbstractFileClient<Config>) clients.get(clientName);
        if (client == null) {
            client = this.createFileClient0(clientName, config);
            client.init();
            clients.put(client.getClientName(), client);
        }
    }

    @SuppressWarnings("unchecked")
    private <Config extends FileClientConfig> AbstractFileClient<Config> createFileClient0(String clientName, Config config) {
        FileStorageEnum storageEnum = FileStorageEnum.getByClientName(clientName);
        Assert.notNull(storageEnum, String.format("暂不支持(%s)的存储类型", clientName));
        // 创建客户端
        return (AbstractFileClient<Config>) ReflectUtil.newInstance(storageEnum.getClientClass(), clientName, config);
    }
}
